package edu.DBUtil;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import edu.tts.domain.Train;
public class JdbcTemplate<T>{
	public static int update(String sql,Object...param) {
		int rowNum = 0;
		Connection connection=DBConnection.getConnection();
		try {
			PreparedStatement pst = connection.prepareStatement(sql);
			ParameterMetaData pmd =  pst.getParameterMetaData();
			if(null!=param&&param.length!=0&&pmd.getParameterCount()==param.length) {
				for(int i=0,len=param.length;i<len;i++)
				{
					pst.setObject(i+1, param[i]);
				}
			}
			rowNum=pst.executeUpdate();
		} catch (Exception e) {
			System.out.println("update operation error,message is "+e.getMessage());
		}finally {
			DBConnection.CloseConnection(connection); 
		}
		return rowNum;
	}
	public static <T> T query(String sql,ResultSetHandler<T> rsh,Object...param) {
		T t=null;
		Connection connection=DBConnection.getConnection();
		try {
			PreparedStatement pst = connection.prepareStatement(sql);
			ParameterMetaData pmd =  pst.getParameterMetaData();
			if(null!=param&&param.length!=0&pmd.getParameterCount()==param.length) {
				for(int i=0,len=param.length;i<len;i++)
				{
					pst.setObject(i+1, param[i]);
				}
			}
			ResultSet rs=pst.executeQuery();
			t=rsh.handler(rs);
		} catch (Exception e) {
			System.out.println("query operation error,message is "+e.getMessage());
		}finally {
			DBConnection.CloseConnection(connection); 
		}
		return t;
	}

}
